package com.declum.archon.chunkserver.manager;

import java.io.DataInputStream;
import java.util.Hashtable;

import com.declum.archon.chunkserver.manager.disk.DiskManager;
import com.declum.archon.chunkserver.manager.disk.IDiskManager;
import com.declum.archon.chunkserver.manager.disk.IDiskOperator;
import com.declum.archon.chunkserver.manager.disk.chunk.ChunkInfo;
import com.declum.archon.chunkserver.manager.disk.streams.ChunkInputStream;

public class ChunkManager implements IChunkManager {
	Hashtable<String, ChunkInfo>	chunkInfoTable	= new Hashtable<String, ChunkInfo>();
	IDiskManager					diskmanager;

	@Override
	public ChunkInfo getChunkInfo(String chunkid) {
		return this.chunkInfoTable.get(chunkid);
	}

	@Override
	public synchronized ChunkInfo createChunk(String chunkid) throws Exception {
		if (this.chunkInfoTable.containsKey(chunkid)) {
			throw new Exception("Chunk " + chunkid + " already exists");
		}
		IDiskOperator freeDisk = this.diskmanager.getFreeDisk();
		IChunkMetaOperator chunkMetaOperator = freeDisk.getChunkMetaOperator();
		ChunkInfo createChunk = chunkMetaOperator.createChunk(chunkid);
		this.chunkInfoTable.put(chunkid, createChunk);
		return createChunk;
	}

	@Override
	public void setDiskManager(IDiskManager manager) {
		this.diskmanager = manager;
		for (IDiskOperator info : manager.getDiskInfo()) {
			ChunkInfo[] allChunkInfo = info.getChunkMetaOperator()
					.getAllChunkInfo();
			for (ChunkInfo chunkInfo : allChunkInfo) {

				this.chunkInfoTable.put(chunkInfo.getChunkid(), chunkInfo);
				System.out.println(chunkInfo.getChunkid());
			}
		}
	}

	public static void main(String[] args) throws Exception {
		IDiskManager manager = new DiskManager();
		manager.addDisk("C:\\temp\\disk1");
		manager.addDisk("D:\\temp\\disk2");
		manager.addDisk("E:\\temp\\disk3");

		IChunkManager chunkManager = new ChunkManager();
		chunkManager.setDiskManager(manager);
		for (int i = 0; i < 1000; i++) {
			// chunkManager.createChunk("" + i);
		}

		ChunkInfo chunkInfo = chunkManager.getChunkInfo("981");
		/*
		 * OutputStream createOutputStream = chunkInfo.createOutputStream();
		 * DataOutputStream out = new DataOutputStream(createOutputStream);
		 * out.write("Clement JebaKumar.C".getBytes()); out.close();
		 */
		DataInputStream in = new DataInputStream(chunkInfo
				.createInputStream(ChunkInputStream.VERIFIED_MODE));
		byte[] data = new byte[1024];
		int count = in.read(data);
		System.out.println(new String(data, 0, count));
	}

	@Override
	public boolean isChunkFound(String chunkid) throws Exception {
		return this.chunkInfoTable.containsKey(chunkid);
	}
}
